package com.example.gouwu2;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

public class CartAdapter extends BaseAdapter {
    private Context context;
    private List<CartManager.CartItem> cartItems;

    public CartAdapter(Context context, List<CartManager.CartItem> cartItems) {
        this.context = context;
        this.cartItems = cartItems;
    }

    @Override
    public int getCount() {
        return cartItems.size();
    }

    @Override
    public Object getItem(int position) {
        return cartItems.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;

        if (convertView == null) {

            convertView = LayoutInflater.from(context).inflate(R.layout.item_cart, parent, false);
            // 初始化ViewHolder
            holder = new ViewHolder();
            holder.ivProduct = convertView.findViewById(R.id.ic_img);
            holder.tvTitle = convertView.findViewById(R.id.ic_title);
            holder.tvPrice = convertView.findViewById(R.id.ic_price);
            // 将ViewHolder存储在视图中
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        //  获取当前商品数据
        CartManager.CartItem item = cartItems.get(position);
        //  绑定数据到视图
        holder.ivProduct.setImageResource(item.getImageRes());
        holder.tvTitle.setText(item.getTitle());
        holder.tvPrice.setText(item.getPrice());

        return convertView;
    }

    static class ViewHolder {
        ImageView ivProduct;
        TextView tvTitle;
        TextView tvPrice;
    }
}